package demo;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ArrayBlockingQueue;
@Slf4j
public class ArrayBlockingQueuePerformanceTest {

    private static final int QUEUE_CAPACITY = 1000000;
    private static final int NUM_PRODUCERS = 2;
    private static final int NUM_CONSUMERS = 2;
    private static final int NUM_MESSAGES = QUEUE_CAPACITY / NUM_PRODUCERS;

    public static void main(String[] args) {
        ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(QUEUE_CAPACITY);

        for (int i = 0; i < NUM_PRODUCERS; i++) {
            new Producer(queue, NUM_MESSAGES).start();
        }

        for (int i = 0; i < NUM_CONSUMERS; i++) {
            new Consumer(queue, NUM_MESSAGES).start();
        }
    }

    private static class Producer extends Thread {
        private final ArrayBlockingQueue<Integer> queue;
        private final int numMessages;

        public Producer(ArrayBlockingQueue<Integer> queue, int numMessages) {
            this.queue = queue;
            this.numMessages = numMessages;
        }

        @Override
        public void run() {
            for (int i = 0; i < numMessages; i++) {
                try {
                    queue.put(i);
                    log.debug("Produced {}",i);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    return;
                }
            }
        }
    }

    private static class Consumer extends Thread {
        private final ArrayBlockingQueue<Integer> queue;
        private final int numMessages;

        public Consumer(ArrayBlockingQueue<Integer> queue, int numMessages) {
            this.queue = queue;
            this.numMessages = numMessages;
        }

        @Override
        public void run() {
            for (int i = 0; i < numMessages; i++) {
                try {
                    Integer msg = queue.take();
                    log.debug("Consumed {}",msg);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    return;
                }
            }
        }
    }
}

